<template>
  <div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      :immediate-check="false"
      finished-text="没有更多了"
      offset="50"
      @load="onLoad"
    >
      <!-- 文章列表 -->
      <article-item
        v-for="item in articlesList"
        :key="item.art_id"
        :obj="item"
        @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
      ></article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from './components/ArticleItem.vue'
import { articlesListAPI } from '@/api'
// 引入
import { timeAgo } from '@/utils/date.js'
export default {
  components: {
    ArticleItem
  },
  props: {
    // 接收父组件传过来的值
    cal: Number
  },
  data () {
    return {
      articlesList: [],
      loading: false,
      finished: false,
      nextTime: null, // 用于加载更多(分页)
      refreshing: false
    }
  },
  // 注册使用
  methods: {
    timeAgo,
    // 封装getArticleList方法用于接口请求
    async getArticleList () {
      const res = await articlesListAPI({
        channelId: this.cal,
        timestamp: this.nextTime
      })
      // console.log(res)
      // console.log(res.data.data.results)
      // 将数据进行处理，把时间转成多久多久之前
      res.data.data.results.forEach((item) => {
        item.pubdate = this.timeAgo(item.pubdate)
      })
      // 如果无数据
      if (res.data.data.results.length === 0) {
        // 告诉list组件直接底部显示没有更多数据
        this.finished = true
      } else {
        // 保存下一页数据的时间(做分页用)
        this.nextTime = res.data.data.pre_timestamp
        this.articlesList = [...this.articlesList, ...res.data.data.results]
        // 等待数据加载完毕后
        this.loading = false
      }
    },
    onLoad () {
      // 触发onLoad时调用数据请求方法
      if (this.articlesList.length > 0) {
        this.getArticleList()
      }
    },
    // 下拉刷新
    onRefresh () {
      // 分页变成空
      this.nextTime = null
      // 数据清空
      this.articleList = []
      // 调用请求接口
      this.getArticleList()
      // 等待数据加载完毕后
      this.refreshing = false
    }
  },
  async created () {
    // 调用数据请求方法
    this.getArticleList()
  }
}
</script>
